package com.qiangesoft.blog.file.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * minio自动配置
 *
 * @author qiange
 * @date 2023-04-21
 */
@Configuration
@ConditionalOnClass(value = {MinioClient.class})
@ConditionalOnProperty(prefix = "file.store", name = "type", havingValue = "FILE_MINIO")
@Slf4j
public class MinioConfiguration {

    private final FileStoreConfig fileStoreConfig;

    public MinioConfiguration(FileStoreConfig fileStoreConfig) {
        this.fileStoreConfig = fileStoreConfig;
    }

    @Bean
    @ConditionalOnMissingBean
    public MinioClient minioClient() {
        FileStoreConfig.MinioConfig minioConfig = fileStoreConfig.getMinioConfig();
        log.info("MinioClient initializing, url is {}, accessKey is {}!", minioConfig.getEndpoint(), minioConfig.getAccessKey());
        MinioClient minioClient = MinioClient
                .builder()
                .endpoint(minioConfig.getEndpoint())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                .build();

        // 设置超时时间
        minioClient.setTimeout(
                minioConfig.getConnectTimeout(),
                minioConfig.getWriteTimeout(),
                minioConfig.getReadTimeout()
        );

        // 初始化创建桶
        if (minioConfig.isCheckBucket()) {
            String bucketName = minioConfig.getBucket();
            if (!checkBucket(bucketName, minioClient)) {
                if (minioConfig.isCreateBucket()) {
                    createBucket(bucketName, minioClient);
                }
            }
        }

        log.info("MinioClient initialization success!");
        return minioClient;
    }

    /**
     * 检查桶是否存在
     *
     * @param bucketName
     * @param minioClient
     * @return
     */
    private boolean checkBucket(String bucketName, MinioClient minioClient) {
        boolean isExists;
        try {
            isExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException("failed to check if the bucket exists", e);
        }
        return isExists;
    }

    /**
     * 创建桶
     *
     * @param bucketName
     * @param minioClient
     */
    private void createBucket(String bucketName, MinioClient minioClient) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException("failed to create default bucket", e);
        }
    }
}
